//
//  RegisterViewController.m
//  HuiPinZhiJia
//
//  Created by MS on 16/9/6.
//  Copyright © 2016年 MS. All rights reserved.
//

#import "RegisterViewController.h"
#import "MBProgressHUD.h"
#import "Appdelegate.h"
@interface RegisterViewController ()
{
    NSInteger _time;
    NSTimer *_timer;
    NSString *info1;
}
@end

@implementation RegisterViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
//发送验证码
- (IBAction)verifyBtn:(id)sender {
    
    [self.verifyBtn setTitle:@"(60s)后重新获取" forState:UIControlStateNormal];
    [self.verifyBtn setBackgroundColor:[UIColor grayColor]];
    self.verifyBtn.enabled = NO;
    if ([self isPhoneNumber])
    {
        [[NetWorking sharedManager] postParameters:@{@"mobile":_phoneTextField.text} type:[NetWorking sharedManager].sendVerify progressValue:^(double value) {
            
        } success:^(id info) {
            MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"验证码发送成功!"];
            [HUD hide:YES afterDelay:0.5];
            SLLog(@"%@",info);
            info1 = [info objectForKey:@"data"];
        } failure:^(id error) {
            MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"验证码发送失败"];
            [HUD hide:YES afterDelay:0.5];
        }];
    }else
    {
        MBProgressHUD * HUD = [(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"请输入正确的手机号"];
        [HUD hide:YES afterDelay:0.5];
    }
    [self addTime];
}

- (void)addTime
{
    _time = 60;
    if (_timer==nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
        //添加到主运行循环
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

//删除定时器
-(void)removeNSTimer
{
    //在invalidate之前最好先用isValid先判断是否还在线程中：
    if ([_timer isValid] == YES) {
        [_timer invalidate];
        _timer = nil;
    }
}

-(void)updateTime{
    _time-=1;
    if (_time==0)
    {
        self.verifyBtn.enabled=YES;
        [self.verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.verifyBtn.backgroundColor= [UIColor colorWithRed:0.95 green:0.58 blue:0.20 alpha:1.00];
        [self removeNSTimer];
    }else{
        [self.verifyBtn setTitle:[NSString stringWithFormat:@"(%ld秒)后重新获取",(long)_time] forState:UIControlStateNormal];
    }
}
//发送注册
- (IBAction)registerBtn:(id)sender {
    if ([_verifyTextField.text isEqualToString:[NSString stringWithFormat:@"%@",info1]])
    {
        [self sendRequestWithMoble:self.phoneTextField.text];
    }else
    {
        MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"验证码错误╮(╯_╰)╭"];
        [HUD hide:YES afterDelay:1];
    }
    
}
-(void)sendRequestWithMoble:(NSString *) moble{
    __weak typeof(self) weakSelf=self;
    NSDictionary * dic=@{@"mobile":moble};
    [[NetWorking sharedManager] postParameters:dic type:[NetWorking sharedManager].oneKeyLogin progressValue:^(double value){
    } success:^(id info){
        SLLog(@"%@",info);
        if ([info[@"status"] integerValue]==1) {
            [[NSUserDefaults standardUserDefaults] setObject:moble forKey:@"userName"];
            
            [[NSUserDefaults standardUserDefaults] setObject:info[@"data"][@"token"] forKey:@"token"];
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isAutoLogin"];
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isLoginSuccess"];
            //实名认证
            [[NSUserDefaults standardUserDefaults]setObject:info[@"data"][@"is_certification"] forKey:@"is_certification"];
            
            MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"注册成功!"];
            [HUD hide:YES afterDelay:1];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"目前已默认您的登录密码为您手机号，为了您的账号安全，请尽快修改您的密码。" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
            UIAlertAction *okBtn = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                
            }];
            [alert addAction:cancelBtn];
            [alert addAction:okBtn];
            [self presentViewController:alert animated:NO completion:nil];
            
        }else if([info[@"status"] integerValue]==2){
            [[NSUserDefaults standardUserDefaults] setObject:moble forKey:@"userName"];
            
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@",info[@"data"][@"token"]] forKey:@"token"];
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isAutoLogin"];
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isLoginSuccess"];
            //实名认证
            [[NSUserDefaults standardUserDefaults]setObject:info[@"data"][@"is_certification"] forKey:@"is_certification"];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:info[@"info"]];
            [HUD hide:YES afterDelay:1];
           
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else{
            MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:info[@"info"]];
            [HUD hide:YES afterDelay:1];
        }
    }failure:^(id info){
        MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"网络错误!"];
        [HUD hide:YES afterDelay:1];
    }];
}
#pragma mark -- 判断是否为手机号
-(BOOL)isPhoneNumber
{
    //手机号筛选
    NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"^[1][358][0-9]{9}" options:0 error:nil];
    if (regex) {
        NSTextCheckingResult * resulte = [regex firstMatchInString:self.phoneTextField.text options:0 range:NSMakeRange(0,self.phoneTextField.text.length)];
        if (resulte) {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
